package com.example.sharesinfo.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseApp;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.PossibleWordsBean;
import com.example.sharesinfo.bean.SimilarQuestionBean;

import com.example.sharesinfo.db.ChatHistory;
import com.example.sharesinfo.db.Questions;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.LitePalHelper;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.squareup.leakcanary.RefWatcher;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class AIActivity extends BaseUIActivity implements View.OnClickListener {
    private static final String LOGTAG = "AIActivity:";
    private static final int GETQUESTIONLISTSUCCESS = 1001;
    private static final int GETQUESTIONLISTFAILED = 1002;
    private static final int GetQuestionDetailSuccess = 1003;
    private static final int GetQuestionDetailFailed = 1004;
    private static final int GetPossibleWordsSuccess = 1005;
    private static final int GetPossibleWordsFailed = 1006;

    private ImageButton ib_return;
    private RecyclerView mAIView;
    private RecyclerView mHistoryView;
    private LinearLayout ll_history;
    private EditText et_input_msg;
    private Button btn_send_msg;
    private String inputText;
    //左边客服回答
    public static final int TYPE_LEFT_TEXT = 0;
    //客服推荐问题列表
    public static final int TYPE_LEFT_LIST = 1;
    //右边自己
    public static final int TYPE_RIGHT_TEXT = 2;
    //自己的头像
    private String meUserPhoto;
    private Disposable disposable;
    private CommonAdapter<ChatHistory> mChatAdapter;
    private CommonAdapter<PossibleWordsBean> mRecommendAdapter;
    private CommonAdapter<Questions> adapter;
    private List<ChatHistory> mList = new ArrayList<>();
    private List<Questions> mQuestionList = new ArrayList<>();
    private List<PossibleWordsBean> mRecommendList = new ArrayList<>();
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case GETQUESTIONLISTSUCCESS:
                    SimilarQuestionBean result = (SimilarQuestionBean) msg.obj;
                    List<Questions> dataBean = new ArrayList<>();
                    for (int i = 0; i < result.getData().size(); i++) {
                        Questions question = new Questions();
                        // question.setId(id + 1 + i);
                        question.setQuestionId(String.valueOf(result.getData().get(i).getId()));
                        question.setQuestion(result.getData().get(i).getQuestion());
                        LogUtils.i(LOGTAG + result.getData().get(i).getQuestion());
                        dataBean.add(question);
                    }
                    LitePalHelper.getInstance().saveHistory(inputText, TYPE_LEFT_LIST, dataBean);
                    int id = LitePalHelper.getInstance().findLast().getId();
                    for (int i = 0; i < dataBean.size(); i++) {
                        Questions question = dataBean.get(i);
                        dataBean.remove(i);
                        question.setId(id - dataBean.size() + i);
                        question.setQuestionId(String.valueOf(result.getData().get(i).getId()));
                        question.setQuestion(result.getData().get(i).getQuestion());
                        dataBean.add(i, question);
                    }
                    addList(dataBean);
                    break;
                case GETQUESTIONLISTFAILED:
                    String answer = String.valueOf(msg.obj);
                    LitePalHelper.getInstance().saveHistory(answer, TYPE_LEFT_TEXT, null);
                    addText(0, answer);
                    break;
                case GetQuestionDetailSuccess:
                    JSONObject result1 = (JSONObject) msg.obj;
                    try {
                        String message = result1.getString("Question") + "答: " + result1.getString("Answer");
                        LitePalHelper.getInstance().saveHistory(message, TYPE_LEFT_TEXT, null);
                        addText(0, message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case GetQuestionDetailFailed:

                    break;
                case GetPossibleWordsSuccess:
                    JSONArray array = (JSONArray) msg.obj;
                    for (int i = 0; i < array.length(); i++) {
                        try {
                            PossibleWordsBean bean = new PossibleWordsBean();
                            JSONObject object = array.getJSONObject(i);
                            bean.setId(Integer.parseInt(object.getString("Id")));
                            bean.setAnswer(object.getString("Answer"));
                            LogUtils.i(LOGTAG + "推荐问题:" + object.getString("Question"));
                            bean.setQuestion(object.getString("Question"));
                            mRecommendList.add(bean);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mRecommendAdapter.notifyDataSetChanged();
                    }
                    break;
                case GetPossibleWordsFailed:
                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ai);
        initView();
        //LitePalHelper.getInstance().delHistory();
        queryHistory();
        getPossibleWords();
        if (SpUtils.getInstance().getString(Constants.IS_FIRST_AI, "").equals("")) {
            addText(0, "你好，我是智能客服阿财，有问题尽管问！");
            LitePalHelper.getInstance().saveHistory("你好，我是智能客服阿财，有问题尽管问！", TYPE_LEFT_TEXT, null);
            SpUtils.getInstance().putString(Constants.IS_FIRST_AI, "true");
        }
    }

    private void initView() {

        meUserPhoto = SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, "");
        ib_return = findViewById(R.id.ib_return);
        ib_return.setOnClickListener(this);
        mAIView = findViewById(R.id.mAIView);
        mHistoryView = findViewById(R.id.mHistoryView);
        ll_history = findViewById(R.id.ll_history);
        et_input_msg = findViewById(R.id.et_input_msg);
        btn_send_msg = findViewById(R.id.btn_send_msg);
        btn_send_msg.setOnClickListener(this);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);//设置为横向排列
        mHistoryView.setLayoutManager(layout);
        mRecommendAdapter = new CommonAdapter<>(mRecommendList, new CommonAdapter.OnBindDataListener<PossibleWordsBean>() {
            @Override
            public void onBindViewHolder(final PossibleWordsBean model, final CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setText(R.id.tv_history, model.getQuestion().replace("\n", "").replace("\r", ""));
                final TextView textView = viewHolder.getView(R.id.tv_history);
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textView.setTextColor(Color.GRAY);
                        addText(1, model.getQuestion().replace("\n", ""));
                        LitePalHelper.getInstance().saveHistory(model.getQuestion().replace("\n", ""), TYPE_RIGHT_TEXT, null);
                        addText(0, model.getQuestion().replace("\n", "") + "\n" + "答:" + model.getAnswer());
                        LitePalHelper.getInstance().saveHistory(model.getQuestion().replace("\n", "") + "\n" + "答:" + model.getAnswer(), TYPE_LEFT_TEXT, null);
                        viewHolder.itemView.setClickable(false);
                        //Toast.makeText(AIActivity.this, model.getQuestion() + model.getAnswer(), Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_ai_history_text_item;
            }
        });
        mHistoryView.setAdapter(mRecommendAdapter);


        mAIView.setLayoutManager(new LinearLayoutManager(this));
        mChatAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnMoreBindDataListener<ChatHistory>() {
            @Override
            public int getItemType(int position) {
                return mList.get(position).getType();
            }

            @Override
            public void onBindViewHolder(ChatHistory model, CommonViewHolder viewHolder, int type, int position) {
                switch (model.getType()) {
                    case TYPE_LEFT_TEXT:
                        viewHolder.setText(R.id.tv_left_text, model.getText());
                        //头像默认的客服头像不要设置
                        break;
                    case TYPE_RIGHT_TEXT:
                        viewHolder.setText(R.id.tv_right_text, model.getText());
                        viewHolder.setImageUrl(AIActivity.this, R.id.iv_right_photo, meUserPhoto);
                        break;
                    case TYPE_LEFT_LIST:
                        if (mQuestionList.size() > 0) {
                            mQuestionList.clear();
                        }
                        LogUtils.i(LOGTAG + "model.getList()" + model.getList().size());
                        mQuestionList.addAll(model.getList());
                        RecyclerView view = viewHolder.getView(R.id.mSimilarView);
                        view.setLayoutManager(new LinearLayoutManager(AIActivity.this));
                        adapter = new CommonAdapter<>(mQuestionList, new CommonAdapter.OnBindDataListener<Questions>() {
                            @Override
                            public void onBindViewHolder(final Questions model, final CommonViewHolder viewHolder, int type, int position) {
                                viewHolder.setText(R.id.tv_similar, model.getQuestion());
                                final TextView text = viewHolder.getView(R.id.tv_similar);
                                if (model.getIsClicked() == 0) {
                                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            getQuestionDetail(model.getQuestionId());
                                            text.setTextColor(Color.GRAY);
                                            LitePalHelper.getInstance().updateQuestion(model.getId(), 1);
                                            LogUtils.i(LOGTAG + "点击的listId:" + model.getId());
                                            viewHolder.itemView.setClickable(false);
                                        }
                                    });
                                } else {
                                    text.setTextColor(Color.GRAY);
                                    text.setClickable(false);
                                }

                            }

                            @Override
                            public int getLayoutId(int type) {
                                return R.layout.layout_similar_question_item;
                            }
                        });
                        view.setAdapter(adapter);
                        break;
                }
            }

            @Override
            public int getLayoutId(int type) {
                if (type == TYPE_LEFT_TEXT) {
                    return R.layout.layout_chat_left_text;
                } else if (type == TYPE_RIGHT_TEXT) {
                    return R.layout.layout_chat_right_text;
                } else if (type == TYPE_LEFT_LIST) {
                    //推荐问题列表
                    return R.layout.layout_chat_left_list;
                }
                return 0;
            }
        });
        mChatAdapter.setHasStableIds(true);
        mAIView.setAdapter(mChatAdapter);
    }

    /**
     * 获取问题对应的答案（参数为KnowledgeId（int）和 UserId（int））
     */

    public void getQuestionDetail(String knowledgeId) {
        String url = "http://119.23.221.142/api/customer/GetAnswer?KnowLedgeId=" + knowledgeId + "&UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                LogUtils.i(LOGTAG + s);
                message.what = GetQuestionDetailSuccess;
                message.obj = object;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * @type
     * @explain
     * @author
     * @creat time
     */
    public void getPossibleWords() {
        String url = "http://119.23.221.142/api/customer/GetPossibleWords";
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LOGTAG + s);
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    message.what = GetPossibleWordsSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetPossibleWordsFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 获取智能客服相似问题List
     *
     * @param question
     */
    public void getSimilarQuestionList(String question) {
        LogUtils.i(LOGTAG + "获取智能客服相似问题");
        String url = "http://119.23.221.142/api/customer/GetSimilarQuestionList?Question=" + question;
        LogUtils.i(LOGTAG + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    SimilarQuestionBean bean = new Gson().fromJson(s, SimilarQuestionBean.class);
                    message.what = GETQUESTIONLISTSUCCESS;
                    message.obj = bean;
                    mHandler.sendMessage(message);
                } else {
                    message.what = GETQUESTIONLISTFAILED;
                    message.obj = object.getString("data");
                    mHandler.sendMessage(message);
                }
                LogUtils.i(LOGTAG + s);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 添加数据的基类
     *
     * @param model
     */
    private void baseAddItem(ChatHistory model) {
        mList.add(model);
        mChatAdapter.notifyItemRangeChanged(mList.size() - 1, mList.size() - 1);
        //滑动到底部
        mAIView.scrollToPosition(mList.size() - 1);
    }

    /**
     * 添加相似问题列表
     *
     * @param dataBean 相似列表
     */
    private void addList(List<Questions> dataBean) {
        ChatHistory model = new ChatHistory();
        model.setType(TYPE_LEFT_LIST);
        model.setList(dataBean);
        baseAddItem(model);
    }

    /**
     * 添加文字
     *
     * @param index 0:左边 1:右边
     * @param text
     */
    private void addText(int index, String text) {
        LogUtils.i("ChatA:" + text);
        ChatHistory model = new ChatHistory();
        if (index == 0) {
            model.setType(TYPE_LEFT_TEXT);
        } else {
            model.setType(TYPE_RIGHT_TEXT);
        }
        model.setText(text);
        baseAddItem(model);
    }

    /**
     * 查询本地聊天记录
     */
    public void queryHistory() {
        /**
         * 在子线程中获取聊天记录列表然后在主线程中更新我们的UI
         * RxJava 线程调度
         */


        disposable = Observable.create(new ObservableOnSubscribe<List<ChatHistory>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ChatHistory>> emitter) throws Exception {
                emitter.onNext(LitePalHelper.getInstance().queryHistory());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<ChatHistory>>() {
                    @Override
                    public void accept(List<ChatHistory> chatHistories) throws Exception {
                        //更新UI
                        LogUtils.i(LOGTAG + chatHistories.size());
                        if (CommonUtils.isEmpty(chatHistories)) {
                            for (int i = 0; i < chatHistories.size(); i++) {
                                LogUtils.i("id显示:" + chatHistories.get(i).getId());
                                if (chatHistories.get(i).getType() == TYPE_LEFT_TEXT) {
                                    //客服回复
                                    addText(0, chatHistories.get(i).getText());
                                } else if (chatHistories.get(i).getType() == TYPE_RIGHT_TEXT) {
                                    //我的提问
                                    addText(1, chatHistories.get(i).getText());
                                } else if (chatHistories.get(i).getType() == TYPE_LEFT_LIST) {
                                    //推荐问题
                                    LogUtils.i(LOGTAG + "chatHistories" + chatHistories.get(i).getList().size());
                                    addList(chatHistories.get(i).getList());
                                    //getSimilarQuestionList(aiChatHistories.get(i).getText());
                                }
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.ib_return:
                finish();
                break;
            case R.id.btn_send_msg:
                inputText = et_input_msg.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    return;
                }
                addText(1, inputText);
                LitePalHelper.getInstance().saveHistory(inputText, TYPE_RIGHT_TEXT, null);
                //清空
                getSimilarQuestionList(inputText);
                et_input_msg.setText("");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        RefWatcher refWatcher = BaseApp.getRefWatcher(this);//1
//        refWatcher.watch(this);
    }
}
